package com.yicong.ants.scenic.data

import androidx.core.widget.ContentLoadingProgressBar
import com.cqyc.network.utils.ToastUtils.showLong

data class LoadStateData<T>(
    var state: LoadState = LoadState.COMPLETE,
    var data: T? = null,
    var msg: String = "",
    var code: Int = 0
) {

    enum class LoadState {
        LOADING, COMPLETE, ERROR
    }

    companion object {
        fun loading(): LoadStateData<Any> {
            return LoadStateData(LoadState.LOADING)
        }

        fun <T> complete(data: T, msg: String): LoadStateData<T> {
            return LoadStateData(LoadState.COMPLETE, data, msg)
        }

        fun error(msg: String): LoadStateData<Result<Any>> {
            return LoadStateData(LoadState.ERROR, msg = msg)
        }
    }

    fun onLoading(callback: () -> Unit): LoadStateData<T> {
        if (state == LoadState.LOADING) {
            callback()
        }
        return this
    }

    fun onComplete(toast: Boolean = false, callback: () -> Unit): LoadStateData<T> {
        if (state == LoadState.COMPLETE) {
            if (toast) {
                showLong(msg)
            }
            callback()
        }
        return this
    }


    fun onError(toast: Boolean = false, callback: () -> Unit): LoadStateData<T> {
        if (state == LoadState.ERROR) {
            if (toast) {
                showLong(msg)
            }
            callback()
        }
        return this
    }

    fun bindProgressBar(
        progressBar: ContentLoadingProgressBar,
        toastComplete: Boolean = false,
        toastError: Boolean = true
    ): LoadStateData<T> {
        when (state) {
            LoadState.LOADING -> {
                progressBar.show()
            }
            LoadState.COMPLETE -> {
                progressBar.hide()
                if (toastComplete) {
                    showLong(msg)
                }
            }
            LoadState.ERROR -> {
                progressBar.hide()
                if (toastError) {
                    showLong(msg)
                }
            }
        }
        return this
    }
}
